<template>
  <div id="app">
    <div class="app-container">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <el-form :model="state.queryData" class="filter-form">
          <el-row :gutter="10" >
            <el-col :span="6">
              <el-form-item label="名称">
                <el-input v-model.trim="state.queryData.UserName" placeholder="请输入名称" size="small" clearable />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="编码">
                <el-input v-model.trim="state.queryData.UserCode" placeholder="请输入编码" size="small" clearable />
              </el-form-item>
            </el-col>

            <el-col :span="4">
              <div class="filter-actions">
                <el-button type="primary" @click="conditionEnter">查询</el-button>
                <el-button type="danger" @click="resetQuery">重置</el-button>
              </div>
            </el-col>
          </el-row>

        </el-form>


      </div>

      <!-- 表格工具栏 -->
      <div class="table-container">
        <div class="toolbar">
          <div class="selected-info" v-if="state.selectedRow">
            <i class="el-icon-info"></i>
            已选择: {{ state.selectedRow.UserName }} - {{ state.selectedRow.UserCode }}
          </div>
          <div v-else style="color: #F56C6C; font-weight: 500;">
            <i class="el-icon-warning"></i> 请选择数据进行操作
          </div>

          <div class="toolbar-actions" v-if="state.selectedRow">
            <el-button type="primary" size="small" @click="printHandle(state.selectedRow)">分配客户</el-button>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-wrapper">
          <el-table
              v-loading="state.loading"
              :data="state.table.data"
              style="width: 100%"
              highlight-current-row
              max-height="700px"
              show-overflow-tooltip
              @current-change="selecUpdateChange"
              empty-text="暂无数据"
          >
            <el-table-column type="index" label="序号" width="60" align="center" fixed />

            <el-table-column label="用户编码" prop="UserCode" fixed>
              <template #default="{ row }">
                <el-link type="primary" @click="viewCheck(row)">{{ row.UserCode || '-' }}</el-link>
              </template>
            </el-table-column>

            <el-table-column prop="UserName" label="用户名称" />

            <el-table-column prop="Phone" label="手机号"  />

            <el-table-column prop="Email" label="邮箱"  />
          </el-table>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.table.total"
              :page-size="state.table.pageSize"
              :current-page="state.table.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="pageChange"
          />
        </div>
      </div>
    </div>


    <!-- 历史版本抽屉 -->
    <el-drawer
        v-model="state.drawer.open"
        @close="state.drawer.open=false"
        :title="'客户分配【'+state.selectedRow?.UserName+'】'+state.selectedRow?.UserCode"
        direction="rtl"
        size="50%"
    >
      <CumList :UserCode="state.selectedRow?.UserCode" ></CumList>
    </el-drawer>

  </div>

</template>

<script setup lang="tsx">
import {computed, onMounted, reactive, ref, toRefs} from "vue"
import {getContractInfo, GetCumPageData, GetUserPageData, userRole} from "@/api/base"
import {ChangePass} from "@/api/contract_entry"
import {addSeparator, debounce, parseTime} from "@/utils/util";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import {checkFildsStore} from "@/stores/modules/checkFilds";
import CumList from './components/index.vue'

const tAdaptivePageRef: any = ref(null)

const cubasdoc = cubasdocStore()


const handlEedit = async (row: any)  => {
  clearCondition()
  //调用查询合同详细信息
  let res =await getContractInfo({id: row.Id})

  if (res.Code==="OK"){
    state.formData = res.Data
    if (state.formData.Main.PhasedFile){
      //转换为数组
      state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.split(",")
    }else {
      state.formData.Main.PhasedFile = []
    }
    if (state.formData.Main.Payment.length>0){
      //转换为数组
      state.formData.Main.Payment = state.formData.Main.Payment.split(",")
    }else {
      state.formData.Main.Payment = []
    }
    state.isShowSubBut = true
    state.dialogSelectEnt = true
    state.title = "合同审核"
  }
}

const viewCheck = async (row: any) => {

  clearCondition()
  //调用查询合同详细信息
  let res = await getContractInfo({ id: row.Id })

  if (res.Code === 'OK') {
    state.formData = res.Data
    state.title = '合同详情'
    state.dialogSelectEnt = true
    state.isShowSubBut = false
  }
}

const handleView = async (row: any)  => {
  //调用查询合同详细信息
  let res =await getContractInfo({id: row.Id})

  if (res.Code==="OK"){
    state.formData = res.Data
    state.dialogSelectEnt = true
    state.isShowSubBut = false
    state.title = "查询合同版本--"+row.ContractNum+"-v"+row.versionNum
  }
}


const handleDelete = (row: any) => {

  state.clumTable.data.splice(state.clumTable.data.indexOf(row), 1)
}

//表格配置
const state: any = reactive({
  roleList: [],
  queryData: {
    ContractType:null,//合同类型
    CustCode:null,//客户编码
    CustName:null,//客户名称
    ContractNum:null,//合同号
    CreateFrom:null,
    CreateTo:null,
    Type:null,
    CreateBy:null,//建单人
    IsMoudel:null,
    IsChange:true
  },
  table: {
    border: true,
    total: 0,
    currentPage: 1,
    pageSize: 10,
    layout: "total,sizes, slot, prev, pager, next, jumper",
    prevText: "上一页",
    nextText: "下一页",
    // 接口返回数据
    data: [],
    firstColumn: { type: 'radio', fixed: true },
    // 表头数据
    columns: [
      { prop: 'index', label: '序号', minWidth: 55, slotName: 'index',fixed: 'left' },
      { prop: 'JobNum', label: '工作号', minWidth: 120,slotName: 'JobNum',fixed: 'left' },
      { prop: 'GDStatus', label: '归档状态', minWidth: 90,slotName:'GDStatus'},
      // { prop: 'ContractNum', label: '合同编码', minWidth: 120 },
      { prop: 'CustName', label: '客户名称', minWidth: 200 },
      // { prop: 'ContractName', label: '合同名称', minWidth: 120 },
      { prop: 'ProjectName', label: '项目名称', minWidth: 200 },
      { prop: 'ContractAmount', label: '合同总价(元)', minWidth: 110,slotName: 'ContractAmount' },
      { prop: 'DeliveryDate', label: '交付日期', minWidth: 110, slotName: 'DeliveryDate' },
      // { prop: 'DeliveryLocation', label: '交付地点', minWidth: 160 },
      // { prop: 'CustCode', label: '客户编码', minWidth: 120 },

      // { prop: 'CustAdd', label: '客户地址', minWidth: 200 },
      { prop: 'Type', label: '合同类型', minWidth: 100, slotName: 'Type' },
      { prop: 'IsMoudel', label: '合同模板', minWidth: 100, slotName: 'IsMoudel' },
      { prop: 'State', label: '状态', minWidth: 70, slotName: 'State' },
      { prop: 'IsSale', label: '销售订单', minWidth: 100, slotName: 'IsSale' },
      { prop: 'BGState', label: '变更状态', minWidth: 100, slotName: 'BGState' },

      // { prop: 'BankAccount', label: '银行账户', minWidth: 120 },
      // { prop: 'Tax', label: '税号', minWidth: 200 },
      // { prop: 'BankCode', label: '行号', minWidth: 160 },
      // { prop: 'SigningLocation', label: '签订地点', minWidth: 160 },
      { prop: 'versionNum', label: '版本', minWidth: 60 },

      { prop: 'DDate2', label: '单据日期', minWidth: 100, slotName: 'DDate' },
      { prop: 'createDate', label: '制单时间', minWidth: 145, slotName: 'CreateDate' },
      { prop: 'createBy', label: '建单人', minWidth: 80 },
    ],
    // operator: [
    //   {
    //     text: "编辑",
    //     fun: handlEedit
    //   },
    //   {
    //     text: "删除",
    //     fun: deleteHandles
    //   }
    // ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 300,
      label: "操作"
    }
  },
  loading:false,
  isShowSubBut:true,
  title: "新增合同录入",
  dialogSelectEnt:false,
  //表单
  formData: {
    Main:{},
    SubList:[],
    TremZF:[],
    TremTO:[],
    TremTC:[],
    TremQA:[],
    TremFM:[],
    TremDR:[],
    TremD:[],
    TremOther:[],
    TremYS:[],
    TremBM:[],
    TremJF:[],
    TremBZ:[],
    ContractFile:[],
    Type:"Pass",
  },
  coseData:[],

  clumTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "CinvCode",
        label: "设备编码",
      },
      {
        prop: "CinvName",
        label: "设备名称",
      },
      {
        prop: "CinvAdd",
        label: "规格型号",

      },
      // {
      //   prop: "Price",
      //   label: "单价",
      //   canEdit: true,
      //   configEdit: {
      //     label: "数量",
      //     type: "input",
      //     editComponent: "el-input"
      //   }
      // },
      {
        prop: "Qty",
        label: "数量",
        canEdit: true,
        configEdit: {
          label: "数量",
          type: "input",
          editComponent: "el-input"
        }
      },
      // {
      //   prop: "Amount",
      //   label: "金额",
      //   canEdit: true,
      //   configEdit: {
      //     label: "数量",
      //     type: "input",
      //     editComponent: "el-input"
      //   }
      // },
      {
        prop: "Unit",
        label: "单位",

      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 300,
      label: "操作"
    }
  },
  editTable: {
    border: true,
    firstColumn: { type: "selection" },
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      {
        prop: "CinvCode",
        label: "设备编码",
      },
      {
        prop: "CinvName",
        label: "设备名称",
      },
      {
        prop: "CinvAdd",
        label: "规格型号",

      },
      {
        prop: "Quantity",
        label: "数量",
      },
      {
        prop: "Unit",
        label: "单位",

      },

    ],
    listTypeInfo: {
      furnaceLayerList: [
        {
          label: "上层",
          key: "1"
        },
        {
          label: "中层",
          key: "2"
        },
        {
          label: "下层",
          key: "3"
        }
      ]
    },
    operator: [
      {
        text: "删除",
        fun: handleDelete
      }
    ],
    // 操作列样式
    operatorConfig: {
      fixed: "right", // 固定列表右边（left则固定在左边）
      width: 200,
      label: "操作"
    }
  },

  rules:{
    ContractNum: [
      { required: true, message: '请输入合同编号', trigger: 'blur' },
    ],
    ProjectName: [
      { required: true, message: '请输入项目名称', trigger: 'blur' },
    ],
    CustCode: [
      { required: true, message: '请选择客户', trigger: 'change' },
    ],
    ContractType: [
      { required: true, message: '请选择合同类型', trigger: 'change' },
    ],
    PSType: [
      { required: true, message: '请输入评审类型', trigger: 'blur' },
    ],
    Payment: [
      { required: true, message: '请选择支付款项', trigger: 'change' },
    ],
    BankCode: [
      { required: true, message: '请输入开户行', trigger: 'blur' },
    ],
    BankAccount: [
      { required: true, message: '请输入银行账号', trigger: 'blur' },
    ],
    Tax: [
      { required: true, message: '请输入税号', trigger: 'blur' },
    ],
    IsCompliance: [
      { required: true, message: '请选择标的物是否合规', trigger: 'change' },
    ],
    DeliveryDate: [
      { required: true, message: '请选择交付时间', trigger: 'change' },
    ],
    DeliveryLocation: [
      { required: true, message: '请输入交付地点', trigger: 'blur' },
    ],
    Rate: [
      { required: true, message: '请输入税率', trigger: 'blur' },
    ],
    Unload: [
      { required: true, message: '请选择卸货方式', trigger: 'change' },
    ],
    PackRequirement: [
      { required: true, message: '请输入包装要求', trigger: 'blur' },
    ],
    ContractAmount: [
      { required: true, message: '请输入合同金额', trigger: 'blur' },
    ],
    //UnloadConvention: [
   //   { required: true, message: '请输入补充说明', trigger: 'blur' },
    //],
    SigningLocation: [
      { required: true, message: '请输入签订地点', trigger: 'blur' },
    ],
    IsMoudel: [
      { required: true, message: '请选择合同是否合同模板', trigger: 'change' },
    ],
    Ddate: [
      { required: true, message: '请选择签订日期', trigger: 'blur' },
    ],
    DDate2: [
      { required: true, message: '请选择单据日期', trigger: 'blur' },
    ],
    JobNum: [
      { required: true, message: '工作号', trigger: 'blur' },
    ],
    SaleNum: [
      { required: true, message: '售前号', trigger: 'blur' },
    ],
  },
  defaultSelectVal:[],
  ids:[],
  drawer:{
    open: false,
    title: "历史版本",
    width: "1000px",
    gridData:[],
    queryData:{}
  },
  checkData:{
    dialog:false,
    loading:false,
    data:[],
    title:'审批详情'
  },

  selectedRow:null,
})



//选择项
const cusoptions = ref(cubasdoc.data)

// 最终参数获取
const getQueryData = computed(() => {
  const data = toRefs(state.queryData)

  let UserName = {name: "UserName", value: data.UserName?.value,wheretype:'1'}
  let UserCode = {name: "UserCode", value: data.UserCode?.value,wheretype:'1'}
  //转换查询参数
  let where=[]
  if(data.UserCode && data.UserCode!=''){
    where.push(UserCode)
  }
  if(data.UserName && data.UserName!=''){
    where.push(UserName)
  }
  return {
    PageIndex: data.PageIndex?.value,
    PageSize : data.PageSize?.value,
    where
  }
})




// 点击查询按钮
const resetQuery = () => {
  state.queryData = {
    UserName:null,//用户姓名
    UserCode:null,//用户编码
  }
  state.table.currentPage =1
  state.table.pageSize = 10
  getData(1)
}

// 点击查询按钮
const conditionEnter = (data: any) => {
  state.table.currentPage =1
  state.table.pageSize = 10
  getData(1)
}

// 清空表单
const clearCondition = () => {
  state.formData = {
    Main:{},
    SubList:[],
    TremZF:[],
    TremTO:[],
    TremTC:[],
    TremQA:[],
    TremFM:[],
    TremDR:[],
    TremD:[],
    TremOther:[],
    TremYS:[],
    TremBM:[],
    TremJF:[],
    TremBZ:[],
    ContractFile:[]
  }
}

// 选择当前页码
const pageChange = val => {
  state.table.currentPage = val

  console.log(state.table.currentPage,"page1"  )
  getData(val)
}

// 选择当前页码
const handleSizeChange = val => {

  state.table.pageSize = val;
  console.log(state.table.pageSize,"size1" )
  getData()
}


// 获取数据
const getData = async pageNum => {
  state.loading = true
  getQueryData.value.PageIndex = state.table.currentPage
  getQueryData.value.PageSize= state.table.pageSize
  let data=await GetUserPageData(getQueryData.value);
  if (data.Code==='OK'){
    state.table.data = data.Data
    state.table.total = data.Total
  }
  state.loading = false
}



//过滤单位
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}

function updateContarctInfo (e) {
  //查询过滤合同信息
  let contractInfo = cubasdoc.contractList.find(item=> item.ContractNum===e);
  if (contractInfo){
    //赋值项目名称
    state.formData.EntryName = contractInfo?.ProjectName;
    state.formData.JobNum = contractInfo?.JobNum;

    //调用查询合同详细信息
    findContractInfo(contractInfo.Id)
  }
}

//查询合同详细信息
async function findContractInfo (id) {
  let {Data}=await getContractInfo({id: id})


  if (Data?.SubList){
    //赋值合同明细
    state.editTable.data = Data.SubList

  }
}


//关闭弹窗
function closeDialog() {
  state.dialogSelectEnt = false
  reset()
}

// 添加数据条数
const num = ref(1)
const singleEdit: any = ref(null)

// 重置表单
const reset = () => {

  state.coseData= []
  state.defaultSelectVal=[]
  state.editTable.data=[]
  singleEdit.value?.resetFields()
}


//下拉表格选择数据
const selecUpdateChange = (e) => {
  state.selectedRow = e
}

//校验表单需要定义ref
let formRef =ref({})

const checkFild = checkFildsStore()
// 提交表单

//获取条款内容
const submitForm = debounce(async () => {

  state.loading = true

  if (state.formData.Type==null){
    ElNotification.warning({
      title: '提示',
      message: '请选择审核状态',
      offset: 200,
    })
    state.loading = false
    return
  }

  if (state.formData.Type=='UnPass' && state.formData.ApproveReason==null){
    ElNotification.warning({
      title: '提示',
      message: '请输入审核不通过原因',
      offset: 200,
    })
    state.loading = false
    return
  }
  if (state.formData.Main.PhasedFile.length>0){
    //逗号字符串
    state.formData.Main.PhasedFile = state.formData.Main.PhasedFile.join(',')
  }
  if (state.formData.Main.Payment.length>0){
    //转换为数组
    state.formData.Main.Payment = state.formData.Main.Payment.join(",")
  }

  setTimeout(async () => {
    if (checkFild.filds.length == 0) {
      //校验通过
      let res = await ChangePass(state.formData)
      if (res.Code === 'OK') {
        ElNotification.success({
          title: '提示',
          message: '保存成功',
          offset: 200,
        })
        state.loading = false
        await getData(1)
        closeDialog()
      } else {
        state.loading = false
        ElNotification.error({
          title: '提示',
          message: res.Result,
          offset: 200,
        })
      }
    }
    state.loading = false
  }, 2000)

},false,1000)

async function printHandle(res) {
  state.drawer.open = true
}



//页面加载查询后端数据
onMounted(() => {
  getData(1)
  initRoleList()
})

const initRoleList = async () => {
  let res = await userRole({ VT_ID: '客户分配' })
  state.roleList = res.items
}

</script>

<style lang="scss" scoped>
.app-container {
  margin: 0 auto;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.header {
  padding: 20px 25px;
  background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h1 {
  font-size: 22px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 12px;
}

.header h1 i {
  font-size: 26px;
}

.header .actions {
  display: flex;
  gap: 15px;
}

.filter-container {
  padding: 20px 25px;
  background: white;
  border-bottom: 1px solid #ebeef5;
}

.filter-form {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding-top: 10px;
}

.table-container {
  //padding: 0 25px 25px;
}

.toolbar {
  padding: 15px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar .selected-info {
  color: #409EFF;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-wrapper {
  //border: 1px solid #ebeef5;
  //border-radius: 6px;
  //overflow: hidden;
  //box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.pagination-container {
  padding: 20px 0;
  display: flex;
  justify-content: flex-end;
}

.status-badge {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-open { background: #e6f7ff; color: #1890ff; }
.status-reviewing { background: #f0f7ff; color: #409EFF; }
.status-approved { background: #f6ffed; color: #52c41a; }
.status-closed { background: #fff2f0; color: #f5222d; }

.operation-cell {
  display: flex;
  gap: 10px;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding-top: 20px;
}

.contract-info-section {
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #ebeef5;
}

.info-title {
  font-size: 16px;
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 15px;
  padding-left: 8px;
  border-left: 4px solid #409EFF;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
}

.info-label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  flex: 1;
  color: #303133;
}

.el-tag + .el-tag {
  margin-left: 8px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

@media (max-width: 992px) {
  .filter-form {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }

  .info-grid {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .header .actions {
    width: 100%;
    justify-content: flex-end;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>
